<template>
    <div>
        <!-- 条件查询 -->
        <el-form :inline="true" :model="searchMap" style="margin: 20px;" ref="searchFormRef">
    <el-form-item prop="teacher_id" style="width: 200px;">
      <el-select
        v-model="searchMap.teacher_id"
        placeholder="根据授课教师查询"
        clearable>
        <el-option v-for="option in teacherOptions" :label="option.name" :value="option._id" :key="option._id"/>
      </el-select>
    </el-form-item>
    <el-form-item prop="manager_id" style="width: 200px;">
      <el-select
        v-model="searchMap.manager_id"
        placeholder="根据班级学管查询"
        clearable>
        <el-option v-for="option in managerOptions" :label="option.name" :value="option._id" :key="option._id"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getClassList">查询</el-button>
      <el-button @click="resetForm(searchFormRef)">重置</el-button>
      <el-button type="primary" @click="handlerAdd">新增班级</el-button>
    </el-form-item>
  </el-form>
      <!-- 班级列表 -->
     <el-table :data="classList" style="width: 100%; height: 500px;">
    <el-table-column label="序号" type="index" width="80"></el-table-column>
    <el-table-column label="班级名称" prop="classname"></el-table-column>
    <el-table-column label="授课教师" prop="teacher_id" :formatter="formatTeacher"></el-table-column>
    <el-table-column label="班级学管" prop="manager_id" :formatter="formatManager"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row._id)">
          编辑
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.row._id)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页控件 -->
   <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加/编辑班级弹窗 -->
    <el-dialog v-model="classFormVisible" title="添加/编辑班级" width="500">
    <el-form :model="updateClass" :rules="rules" ref="classFormRef" style="width: 400px;" label-width="100px" label-position="right">
      <el-form-item label="班级名称" prop="classname">
        <el-input v-model="updateClass.classname" />
      </el-form-item>
      <el-form-item label="授课教师" prop="teacher_id">
        <el-select v-model="updateClass.teacher_id" placeholder="请选择授课教师">
          <el-option v-for="option in teacherOptions" :label="option.name" :value="option._id" :key="option._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级学管" prop="manager_id">
        <el-select v-model="updateClass.manager_id" placeholder="请选择班级学管">
          <el-option v-for="option in managerOptions" :label="option.name" :value="option._id" :key="option._id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updateClass._id==null?addData(classFormRef):updateData(classFormRef)">
          确定
        </el-button>
        <el-button @click="classFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { classInfoData } from '@/api/class/type'
import { nextTick, onMounted, reactive, ref } from 'vue'
// 引入班级小仓库
import useClassStore from '@/store/modules/class'
// 引入角色小仓库
import useRoleStore from '@/store/modules/role'
// 引入用户小仓库
import useUserStore from '@/store/modules/user'
import type { roleInfoData } from '@/api/role/type'
import type { userInfoData } from '@/api/user/type'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
// import { formatter } from 'element-plus'

/*
现有内容:请求api方法，数据类型，小仓库
1，显示数据列表 --- 条件筛选
2，添加班级弹窗以及功能
3，编辑弹窗回显以及更新数据
4，删除
*/

// 重置条件查询表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getClassList()
}
// 条件查询表单ref对象
const searchFormRef = ref()

// 添加/编辑班级数据收集对象
const updateClass = ref({
  _id:null,
  classname:'',
  teacher_id:'',
  manager_id:''
})
// 表单ref对象
const classFormRef = ref()
// 表单校验规则
const rules = reactive<FormRules>({
  classname: [{ required:true, message:"请输入班级名称", trigger: 'blur' }],
  teacher_id: [{ required:true, message:"请选择授课教师", trigger: 'blur' }],
  manager_id: [{ required:true, message:"请选择班级学管", trigger: 'blur' }],
})
const addData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      classStore.addClass(updateClass.value).then(()=>{
        classFormVisible.value = false
        getClassList()
      })
    } else {
      console.log('error submit!')
    }
  })
}
const updateData = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      classStore.updateClass(updateClass.value).then(()=>{
        classFormVisible.value = false
        getClassList()
      })
    } else {
      console.log('error submit!')
    }
    })
}
// 表单弹窗初始状态
const classFormVisible = ref(false)

const classStore = useClassStore();
const roleStore = useRoleStore();
const userStore = useUserStore();
// 角色数组
const roleOptions = ref<roleInfoData[]>([]);
// 用户数组
const userOptions = ref<userInfoData[]>([]);
// 教师id
const teacher_role_id = ref("");
// 学管id
const manager_role_id = ref("");
// 教师数组
const teacherOptions = ref<userInfoData[]>([]);
// 学管数组
const managerOptions = ref<userInfoData[]>([]);
// 获取角色数组
const getRoleList = () => {
  return new Promise((resolve,_reject)=>{
    if(roleStore.roles && roleStore.roles.length){
      roleOptions.value = roleStore.roles;
      roleOptions.value.forEach((item)=>{
        if(item.name == "教师"){
          teacher_role_id.value = item._id as string
        }else if(item.name == "学管"){
          manager_role_id.value = item._id as string
        }
      });
      resolve(true)
    }else{
      roleStore.getRoleList().then(()=>{
        roleOptions.value = roleStore.roles;
      roleOptions.value.forEach((item)=>{
        if(item.name == "教师"){
          teacher_role_id.value = item._id as string
        }else if(item.name == "学管"){
          manager_role_id.value = item._id as string
        }
      });
    });
    resolve(true);
  }
});
};
// 获取用户数组
const getUserList = () => {
  return new Promise((resolve,_reject)=>{
    if(userStore.users && userStore.users.length){
      userOptions.value = userStore.users;
      userOptions.value.forEach((item)=>{
        if(item.role_id == teacher_role_id.value){
          teacherOptions.value.push(item)
        }else if(item.role_id == manager_role_id.value){
          managerOptions.value.push(item)
        }
      });
      resolve(true)
    }else{
      userStore.getUserAll().then(()=>{
        userOptions.value = userStore.users;
        userOptions.value.forEach((item)=>{
        if(item.role_id == teacher_role_id.value){
          teacherOptions.value.push(item)
        }else if(item.role_id == manager_role_id.value){
          managerOptions.value.push(item)
        }
      });
    });
    resolve(true)
  }
});
};
// 格式化教师
const formatTeacher = (
  _row:any,
  _colum:any,
  cellValue:string,
  _index:number
)=>{
  let teacher = teacherOptions.value.find(
    (item)=>item._id == cellValue
  );
  return teacher?.name
};
// 格式化学管
const formatManager = (
  _row:any,
  _colum:any,
  cellValue:string,
  _index:number
)=>{
  let manager = managerOptions.value.find(
    (item)=>item._id == cellValue
  );
  return manager?.name
};
const classList = ref<classInfoData[]>([])
// 分页定义
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
// 条件筛选对象
const searchMap = ref({
    teacher_id:'',
    manager_id:''
})
const getClassList = ()=>{
    classStore.getClassList({page:currentPage.value,size:pageSize.value,searchMap:searchMap.value}).then(response=>{
       classList.value= classStore.classes as classInfoData[]
       // @ts-ignore
       total.value = response?.total
    })
}
// 页码变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getClassList()
}
const handleCurrentChange = (val: number) => {
   currentPage.value = val
   getClassList()
}
// 打开新增班级弹窗
const handlerAdd = ()=>{
  classFormVisible.value = true
  updateClass.value = {
    _id:null,
    classname:'',
    teacher_id:'',
    manager_id:''
  }
  nextTick(()=>{
    classFormRef.value.resetFields()
  })
}
const handleEdit = (_id:string) => {
    handlerAdd()
    classStore.getClassById(_id).then((response)=>{
      // @ts-ignore
        updateClass.value = response
    })
}
// 删除方法
const handleDelete = (_id:string) => {
  ElMessageBox.confirm(
    '确认要删除此条数据?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      classStore.deleteClass(_id).then(()=>{
        ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getClassList()
      })
      
    })
    .catch(() => {})
}
onMounted(()=>{
  getRoleList().then(()=>{
    getUserList().then(()=>{
      getClassList()
    })
  })
  // getRoleList()
  // getUserList()
  // getClassList()
})
</script>

<style scoped>

</style>